/*
 * =====================================================================================
 *
 *       Filename:  findborders.cpp
 *
 *    Description:  Returns the contour of a given character (scanning method)
 *
 *        Version:  1.0
 *        Created:  06/07/12 10:35:18
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Moos Hueting (mh), mooshueting@gmail.com
 *   Organization:  
 *
 * =====================================================================================
 */
#include <iostream>
#include <cv.h>
#include <highgui.h>

using namespace std;
using namespace cv;

int main(int argc, char* argv[]) {
    Mat image; 
    Mat border;
    vector<vector<Point> > contours;
    vector<Vec4i> hierarchy;

    image = imread(argv[1], CV_LOAD_IMAGE_GRAYSCALE);
    threshold(image, image, 100, 255, THRESH_BINARY);
    Size s = image.size();

    border = Mat(s.height, s.width, CV_8UC1, Scalar(0));

    findContours(image, contours, hierarchy, CV_RETR_CCOMP, CV_CHAIN_APPROX_NONE);

    for (int i = 0; i < contours.at(0).size(); i++) {
        border.at<unsigned char>(contours.at(0).at(i).y, contours.at(0).at(i).x) = 255;
    }

    resize(border, border, Size(0,0), 10, 10, INTER_NEAREST);

    namedWindow("Display Image", CV_WINDOW_AUTOSIZE);
    imshow("Display Image", border);
    waitKey(0);

}

//int main(int argc, char* argv[]) {
//    Mat image;
//    Mat border;
//
//    image = imread( argv[1], CV_LOAD_IMAGE_GRAYSCALE );
//    threshold(image, image, 100, 255, THRESH_BINARY);
//    Size s = image.size();
//
//    border = Mat(s.height, s.width, CV_8UC1, Scalar(0));
//
//    for (int i = 0; i < s.height; i++) {
//        for (int j = 1; j < s.width; j++) {
//            if (image.at<unsigned char>(i, j) != 0) {
//                border.at<unsigned char>(i, j - 1) = 255;
//                break;
//            }
//        }
//    }
//
//    for (int i = 0; i < s.height; i++) {
//        for (int j = s.width - 2; j >= 0; j--) {
//            if (image.at<unsigned char>(i, j) != 0) {
//                border.at<unsigned char>(i, j + 1) = 255;
//                break;
//            }
//        }
//    }
//
//    for (int i = 0; i < s.width; i++) {
//        for (int j = 1; j < s.height; j++) {
//            if (image.at<unsigned char>(j, i) != 0) {
//                border.at<unsigned char>(j - 1, i) = 255;
//                break;
//            }
//        }
//    }
//
//    for (int i = 0; i < s.width; i++) {
//        for (int j = s.height - 2; j >= 0; j--) {
//            if (image.at<unsigned char>(j, i) != 0) {
//                border.at<unsigned char>(j + 1, i) = 255;
//                break;
//            }
//        }
//    }
//
//    resize(border, border, Size(0,0), 10, 10, INTER_NEAREST);
//
//    namedWindow("Display", CV_WINDOW_AUTOSIZE);
//    imshow("Display", border);
//    waitKey(0);
//}
